// ==UserScript==
// @name         Mark Baidu ads
// @namespace    lantian
// @version      1.0
// @description  Mark Baidu ads
// @author       lantian
// @match        *://www.baidu.com/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';
    // Your code here...
    function I(id, obj) { obj = obj || document; return obj.getElementById(id); }
    function T(tag, obj) { obj = obj || document; return obj.getElementsByTagName(tag); }
    function C(clazz, obj) { obj = obj || document; return obj.getElementsByClassName(clazz); }
    function E(tag) { return document.createElement(tag); }

    var timer = null;
    function handleDomModified(event) {
        var target = event.target;
        if (target && target.getAttribute &&
            (target.getAttribute('id')=='content_left' ||
             target.parentNode.getAttribute('id')) ) {

            if (timer !== null) { clearTimeout(timer); }
            timer = setTimeout(function() {
                console.log('Dom midified');
                document.removeEventListener('DOMSubtreeModified', handleDomModified);
                addAdsNotice();
            }, 200);
        }
    }

    function addAdsNotice() {
        var contentLeft = I('content_left');
        var items = contentLeft ? contentLeft.children : [];
        for(var i=0; i<items.length; i++) {
            var item = items[i];
            if (item.parentNode.getAttribute('id') == 'content_left' &&
                !/广告！/.test(item.innerHTML) &&
                />广告<\/span>/.test(item.innerHTML)) {
                var notice = E('span');
                notice.innerHTML='广告！';
                notice.style='padding: 0px 0px 2px 8px; background-color: darkred; color: white; display: inline-block; border-bottom-right-radius: 5px;';
                item.insertBefore(notice, item.childNodes[0]);
                item.style='border:2px solid darkred; opacity: 0.3;';
            }
        }

        document.addEventListener('DOMSubtreeModified', handleDomModified);
    }
    addAdsNotice();

})();